//
//  GameRandom.h
//  Header only random generator that reads data from /dev/random or /dev/urandom.
//
//  Created by 杨岑 on 7/14/14.
//
//

#ifndef _GameRandom_H_
#define _GameRandom_H_

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

class GameRandom
{
private:
    int _h;
    bool _u;
    
public:
    GameRandom(bool useURandom = true)
    {
        _u = useURandom;
        _h = open(_u ? "/dev/urandom" : "/dev/random", O_RDONLY);
        if (_h == -1)
        {
            printf("GameRandom: unable to open random device (error %d)\n", errno);
        }
    }
    
    ~GameRandom()
    {
        if (_h != -1)
        {
            close(_h);
            _h = -1;
        }
    }
    
    // Although the returned type is 'unsigned', you can treat it as signed.
    unsigned int getRandom()
    {
        if (_h != -1)
        {
            unsigned int r;
            read(_h, &r, sizeof(r));
            return r;
        }
        
        // Worst condition
        return rand();
    }
    
    // The parameter is typed as 'unsigned' but you can safely passs in (-100, 100)
    // and get expected result as long as you do explicit type cast.
    unsigned int getRandom(unsigned int min, unsigned int max)
    {
        return this->getRandom() % (max - min + 1) + min;
    }
};

#endif


